var db;
var missFileMp3 = false;
var missFileJPG = false;

var lessonID = getUrlVars()["leid"];
var listeningLessonIDSelected = getLocalStorage('listeningLessonIDSelected');
var favourite = 0;


if (lessonID == null) {
	if (listeningLessonIDSelected == null) { // //Lan chay dau tien : khong
												// co lessonID va
												// lessonForwardSelected -->load
												// nhung bai doc cua lesson dau
												// tien (mac dinh coi la 1)
		lessonID = 1;
		setLocalStorage('listeningLessonIDSelected',lessonID);
	}else{ // ko phai lan chay dau tien(nhung cung khong co lessonID tren url)
			// -> lay lessonForwardSelected dc luu trong localStorage
		lessonID = listeningLessonIDSelected
	}
}else {// lay chay sau, co lessonID tren url -> cap nhat lai
		// lessonForwardSelected
	setLocalStorage('listeningLessonIDSelected',lessonID);
}


function connectDB() {
	db = window.openDatabase("JapaneseBasic", "1.0", "Japanese Database",500000);
	db.transaction(getListeningDetail, errorCB);
}


// function will be called when an error occurred
function errorCB(err) {
	alert("Error processing SQL: " + err.code);
}

function successCB() {
	db.transaction(getListeningDetail, errorCB);
}

function getListeningDetail(tx) {
	
	var sql = "SELECT li_id, li_title,li_thumb, li_script_jp, li_track, li_script_en, li_script_vi ,li_lesson_id,li_favourite, li_dataversion_id "
			+ " FROM listening " 
			+ " INNER JOIN lesson"
			+ " ON listening.li_lesson_id = lesson.le_id"
			+ " WHERE listening.li_lesson_id =  " + lessonID;
	tx.executeSql(sql, [], showListeningDetail);
}

function showListeningDetail(tx, results) {
	var filePath = localStorage.getItem("listenFilePath");
	// show title
	$('#title-detail').append(results.rows.item(0).li_title);
	
	// Luu li_id vao localStorage -> de dung khi add/remove favourite
	setLocalStorage('listeningIdCurrent',results.rows.item(0).li_id);
	setLocalStorage('curenttrackname',results.rows.item(0).li_track);
	setLocalStorage('curentthumbname',results.rows.item(0).li_thumb);
	// source audio
	if (results.rows.item(0).li_track == null || results.rows.item(0).li_track == '') {
		alert("Dữ liệu hiện chưa được cập nhật. Vô cùng thương tiếc!");
	} else {
		var fullFilePath = filePath+results.rows.item(0).li_track;
		var reader = new FileReader();
		$('#audio-content').append('<center id="audio-player-hihi"><audio controls><source src="'+fullFilePath+'" type="audio/mpeg" /><source src="'+fullFilePath+'" type="audio/ogg" /></audio></center>');
		reader.onloadend = function(evt) {
		    if(evt.target.result == null) {
		    	//nếu không có file
		    	$('#popup-download').css('display','block');
		    	$('#audio-player-hihi').css('display','none');
		    	alert("Dữ liệu file nghe cho bài này bi lỗi, xin vui lòng tải lại!");
		    }else{
		    	//$('#audio-content').append('<center id="audio-player-hihi"><audio controls><source src="'+fullFilePath+'" type="audio/mpeg" /><source src="'+fullFilePath+'" type="audio/ogg" /></audio></center>');
		    }         
		};
		// We are going to check if the file exists
		reader.readAsDataURL(fullFilePath); 
	}
	
	// source image
	if (results.rows.item(0).li_thumb == null || results.rows.item(0).li_thumb == '') {
		// $("#listening-thumb").attr('src','img/no_img.jpg);
		$("#listening-thumb").attr('src','img/no_img.jpg');
	} else {
		var fullFilePath = filePath+results.rows.item(0).li_thumb;
		var imageName = results.rows.item(0).li_thumb;
		$("#listening-thumb").attr('src',fullFilePath);
		
		var reader = new FileReader();

		reader.onloadend = function(evt) {
		    if(evt.target.result == null) {
		    	alert("Dữ liệu file hình bị lỗi hoặc thiếu, xin vui lòng click vào hình ảnh NoImage để download lại!");
		       // If you receive a null value the file doesn't exists
		    	$("#listening-thumb").attr('src','img/no_img.jpg');
		    	$("#listening-thumb").attr('onclick','checkConnectThumb();');
		    }     
		};
		
		// We are going to check if the file exists
		reader.readAsDataURL(fullFilePath); 
		
	}
	
	// content js
	if (results.rows.item(0).li_script_jp == null
			|| results.rows.item(0).li_script_jp == '') {
		$('#content-jp').append(
				'<div style="margin: 20px; 20px;">Updating...</div>');
	} else {
		$('#content-jp').append(results.rows.item(0).li_script_jp);
	}
	
	// content en
	if (results.rows.item(0).li_script_en == null
			|| results.rows.item(0).li_script_en == '') {
		$('#content-en').append(
				'<div style="margin: 20px; 20px;">Updating...</div>');
	} else {
		$('#content-en').append(results.rows.item(0).li_script_en);
	}
	
	// content vi
	if (results.rows.item(0).li_script_vi == null || results.rows.item(0).li_script_vi == '') {
		$('#content-vi').append(
				'<div style="margin: 20px; 20px;">Updating...</div>');
	} else {
		$('#content-vi').append(results.rows.item(0).li_script_vi);
	}
	
	// set icon cho favourite button
	if (results.rows.item(0).li_favourite == 1) {
		$('a[task="favouriteTask"]').attr("id","addFavourite");
	}else{
		$('a[task="favouriteTask"]').attr("id"," ");
	}
	
}

function checkConnectKaiWa(){
	 var networkState = navigator.network.connection.type;

		if(networkState == Connection.NONE){
			$( "#khongketnoi-popup" ).popup( "open");
			
		}
		else if(networkState == Connection.CELL_2G || networkState == Connection.CELL_3G || networkState == Connection.CELL_4G){
			//hỏi người dùng có dùng mạng 3g để download không, vì có mấy thằng điên nhiều tiến ngu khôn gbiet dùng wifi
			$( "#celldata-popup" ).popup( "open");
			//alert("co ket noi 3gfi");
		}
		else{
			//khi có kết nối 
			$( "#waiting-popup" ).popup( "open");
			$("#waiting-popup").on({
			    popupbeforeposition: function () {
			        $('.ui-popup-screen').off();
			    }
			});
			downloadMissingKaiwa();
		}
}
function checkConnectThumb(){
	var networkState = navigator.network.connection.type;
	
	if(networkState == Connection.NONE){
		$( "#khongketnoi-popup" ).popup( "open");
		
	}
	else if(networkState == Connection.CELL_2G || networkState == Connection.CELL_3G || networkState == Connection.CELL_4G){
		//hỏi người dùng có dùng mạng 3g để download không, vì có mấy thằng điên nhiều tiến ngu khôn gbiet dùng wifi
		$( "#celldata-popup" ).popup( "open");
		//alert("co ket noi 3gfi");
	}
	else{
		//khi có kết nối 
		$( "#waiting-popup" ).popup( "open");
		$("#waiting-popup").on({
		    popupbeforeposition: function () {
		        $('.ui-popup-screen').off();
		    }
		});
		downloadMissingThumb();
	}
}

function downloadMissingKaiwa(){
	//alert("download: "+ sourUrl);
	var fileTransfer = new FileTransfer();
	var desPath = localStorage.getItem("listenFilePath");
	
	
	fileTransfer.download(
			kaiwaUrl+"/" + getLocalStorage('curenttrackname'),
		   desPath + getLocalStorage('curenttrackname'),
		   downloadCompleteKaiwa,
		   downloadError
	);
}
function downloadMissingThumb(){
	//alert("download: "+ sourUrl);
	var fileTransfer = new FileTransfer();
	var desPath = localStorage.getItem("listenFilePath");
	fileTransfer.download(
			thumbUrl+"/" + localStorage.getItem('curentthumbname'),
			desPath + localStorage.getItem('curentthumbname'),
			downloadCompleteThumb,
			downloadError
	);
}
function downloadCompleteThumb(){
	$( "#waiting-popup" ).popup( "close");
	$("#listening-thumb").attr('src',localStorage.getItem("listenFilePath") + localStorage.getItem('curentthumbname'));
	$("#listening-thumb").attr('onclick','');
	alert("Download file thành công!");
	//cap nhat
}
function downloadCompleteKaiwa(){
	$("#popup-download").css('display', 'none');
	$( "#waiting-popup" ).popup( "close");
	var fullFilePath = localStorage.getItem("listenFilePath") + getLocalStorage('curenttrackname');
	$('#audio-content').append('<center><audio controls><source src="'+fullFilePath+'" type="audio/mpeg" /><source src="'+fullFilePath+'" type="audio/ogg" /></audio></center>');
	alert("Download file thành công!");
	//cap nhat
}
function downloadError(error) {
	   $( "#waiting-popup" ).popup( "close");
	   alert("Download file không thành công!");
	  // $( "#error-popup" ).popup( "open");
	   console.log("download error source " + error.source);
	   console.log("download error target " + error.target);
	   console.log("upload error code: " + error.code);
}
function checkExtensionImageFile(file) {
	var check = false;
    var extension = file.substr( (file.lastIndexOf('.') +1));
    if (extension == 'jpg' || extension == "png" || extension == "gif") {
    	check = true;
	}
    return check;
}